package com.zimper.web.action;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 7872008438201712650L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String submitFlag = request.getParameter("submitFlag");
		if("checkLogin".equals(submitFlag)) {
			login(request, response);
			return;
		}else{
			toLogin(request, response);
		}
	}
	
	private void toLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		String loginPath = request.getContextPath() + "/servletLogin.xhtml";
		PrintWriter write = response.getWriter();
		write.write("<form action='" + loginPath + "' method='post'>");
		write.write("<input type='hidden' name='submitFlag' value='checkLogin'/>");
		write.write("username:<input type='text' name='username'/><br/>");
		write.write("password:<input type='password' name='password'/><br/>");
		write.write("<input type='submit' value='login'/>");
		write.write("</form>");
	}
	
	private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if(checkUser(username, password)) {
			response.getWriter().write("<h1 style='color:red'/>login success!");
		} else {
			response.getWriter().write("<h1>login fail!~~~~(>_<)~~~~");
		}
	}
	
	protected boolean checkUser(String username,String password) {
		if("yaoper".equals(username) && "12345".equals(password)){
			return true;
		}else{
			return false;
		}
	}
}